package app.sevenc.lib_framework.ktx

import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter

/**
 * 给 view / adapter拓展的，防止重复点击item
 *
 * @author Seven-C
 * @date 2020/8/24
 */

var viewLastClickTime = 0L
fun View.setSingleOnClickListener(interval: Long = 1000, action: (view: View) -> Unit) {
    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (viewLastClickTime != 0L && (currentTime - viewLastClickTime < interval)) {
            return@setOnClickListener
        }
        viewLastClickTime = currentTime
        action(it)
    }
}

fun singleAction(interval: Long = 1000, action: () -> Unit) {
    val currentTime = System.currentTimeMillis()
    if (viewLastClickTime != 0L && (currentTime - viewLastClickTime < interval)) {
        return
    }
    viewLastClickTime = currentTime
    action.invoke()
}


var adapterLastClickTime = 0L
fun BaseQuickAdapter<*, *>.setSingleOnItemClickListener(
    interval: Long = 1000,
    action: (adapter: BaseQuickAdapter<*, *>, view: View, position: Int) -> Unit
) {
    setOnItemClickListener { adapter, view, position ->
        val currentTime = System.currentTimeMillis()
        if (adapterLastClickTime != 0L && (currentTime - adapterLastClickTime < interval)) {
            return@setOnItemClickListener
        }
        adapterLastClickTime = currentTime
        action(adapter, view, position)
    }
}


var adapterChildLastClickTime = 0L
fun BaseQuickAdapter<*, *>.setSingleOnItemChildClickListener(
    interval: Long = 1000,
    action: (adapter: BaseQuickAdapter<*, *>, view: View, position: Int) -> Unit
) {
    setOnItemChildClickListener { adapter, view, position ->
        val currentTime = System.currentTimeMillis()
        if (adapterChildLastClickTime != 0L && (currentTime - adapterChildLastClickTime < interval)) {
            return@setOnItemChildClickListener
        }
        adapterChildLastClickTime = currentTime
        action(adapter, view, position)
    }
}